<template>
  <div class="home-page">
    <!-- 用户信息卡片 -->
    <div class="user-info-card">
      <div class="user-avatar">
        <van-image
          round
          width="60"
          height="60"
          src="https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg"
          alt="用户头像"
        />
      </div>
      <div class="user-details">
        <div class="user-name">{{ userName }}</div>
        <div class="user-phone">{{ userPhone }}</div>
      </div>
    </div>

    <!-- 考试数据概览 -->
    <div class="data-overview">
      <div class="overview-card">
        <div class="overview-value">{{ examStats.ongoing }}</div>
        <div class="overview-label">进行中考试</div>
      </div>
      <div class="overview-card">
        <div class="overview-value">{{ examStats.upcoming }}</div>
        <div class="overview-label">即将开始</div>
      </div>
      <div class="overview-card">
        <div class="overview-value">{{ examStats.completed }}</div>
        <div class="overview-label">已完成考试</div>
      </div>
    </div>

    <!-- 快捷操作 -->
    <div class="quick-actions">
      <van-button
        icon="guide-o"
        type="primary"
        size="large"
        @click="goToExamList"
        block
      >
        参加考试
      </van-button>
    </div>

    <!-- 最近考试 -->
    <div class="recent-exams">
      <div class="section-title">
        <span>最近考试</span>
        <van-button
          plain
          hairline
          type="primary"
          size="small"
          @click="goToHistory"
        >
          查看全部
        </van-button>
      </div>

      <div v-if="loading" class="loading-container">
        <van-loading type="spinner" size="24px" />
      </div>

      <template v-else>
        <!-- 最近考试列表 -->
        <div v-if="recentExams.length > 0" class="exam-list">
          <div
            v-for="exam in recentExams"
            :key="exam._id"
            class="exam-card"
            @click="goToExamDetail(exam._id)"
          >
            <div class="exam-info">
              <div class="exam-name">{{ exam.exam_name }}</div>
              <div class="exam-time">
                {{ formatDate(exam.start_time) }} -
                {{ formatDate(exam.end_time) }}
              </div>
            </div>
            <div class="exam-status" :class="getStatusClass(exam)">
              {{ getStatusText(exam) }}
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-else class="empty-state">
          <van-empty description="暂无考试记录" />
        </div>
      </template>
    </div>

    <!-- 底部导航 -->
    <van-tabbar route>
      <van-tabbar-item icon="home-o" to="/home">首页</van-tabbar-item>
      <van-tabbar-item icon="notes-o" to="/history">历史</van-tabbar-item>
      <van-tabbar-item icon="user-o" to="/profile">我的</van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script setup lang="ts">
import {
  computed,
  onMounted,
  ref,
} from 'vue';

import { showToast } from 'vant';
import { useRouter } from 'vue-router';

import type { IExam } from '@shared/types/exam';

import { useExamStore } from '../../stores/exam';
import { useUserStore } from '../../stores/user';

const router = useRouter();
const userStore = useUserStore();
const examStore = useExamStore();

const loading = ref(true);
const recentExams = ref<IExam[]>([]);

// 用户信息
const userName = computed(() => userStore.user?.username || "用户");
const userPhone = computed(() => userStore.user?.phone || "未绑定手机");

// 考试统计
const examStats = ref({
  ongoing: 0,
  upcoming: 0,
  completed: 0,
});

// 获取数据
onMounted(async () => {
  try {
    // 检查登录状态
    console.log("用户登录状态:", {
      isLoggedIn: userStore.isLoggedIn,
      token: userStore.token
        ? `${userStore.token.substring(0, 10)}...`
        : "null",
      user: userStore.user,
    });

    // 如果没有token，直接跳转到登录页
    if (!userStore.isLoggedIn) {
      console.log("用户未登录，跳转到登录页");
      router.replace('/login');
      return;
    }

    // 获取用户信息
    if (!userStore.user) {
      await userStore.getUserInfo();
    }

    // 获取考试列表
    await examStore.fetchExamList();

    // 处理考试数据
    processExamData();
  } catch (error: any) {
    console.error("获取数据失败", error);
    
    // 如果是401错误，说明token无效，清除认证状态并跳转登录
    if (error.response?.status === 401 || error.message?.includes('401')) {
      console.log("认证失败，清除登录状态并跳转到登录页");
      userStore.clearAuth();
      router.replace('/login');
      return;
    }
    
    showToast({
      message:"数据加载失败",
      duration:1000,
    });
  } finally {
    loading.value = false;
  }
});

// 处理考试数据
const processExamData = () => {
  if (!examStore.examList) return;

  // 当前时间
  const now = new Date().getTime();

  // 统计各类考试数量
  let ongoing = 0;
  let upcoming = 0;
  let completed = 0;

  // 排序考试列表（按开始时间倒序）
  const sortedExams = [...examStore.examList].sort((a, b) => {
    return new Date(b.start_time).getTime() - new Date(a.start_time).getTime();
  });

  // 统计数量
  sortedExams.forEach((exam) => {
    const startTime = new Date(exam.start_time).getTime();
    const endTime = new Date(exam.end_time).getTime();

    if (now >= startTime && now <= endTime) {
      ongoing++;
    } else if (now < startTime) {
      upcoming++;
    } else {
      completed++;
    }
  });

  // 更新统计数据
  examStats.value = {
    ongoing,
    upcoming,
    completed,
  };

  // 更新最近考试
  recentExams.value = sortedExams.slice(0, 3);
};

// 格式化日期
const formatDate = (dateStr: string) => {
  const date = new Date(dateStr);
  return `${
    date.getMonth() + 1
  }月${date.getDate()}日 ${date.getHours()}:${String(
    date.getMinutes()
  ).padStart(2, "0")}`;
};

// 获取状态文本
const getStatusText = (exam: IExam) => {
  const now = new Date().getTime();
  const startTime = new Date(exam.start_time).getTime();
  const endTime = new Date(exam.end_time).getTime();

  if (now >= startTime && now <= endTime) {
    return "进行中";
  } else if (now < startTime) {
    return "即将开始";
  } else {
    return "已结束";
  }
};

// 获取状态样式类
const getStatusClass = (exam: IExam) => {
  const now = new Date().getTime();
  const startTime = new Date(exam.start_time).getTime();
  const endTime = new Date(exam.end_time).getTime();

  if (now >= startTime && now <= endTime) {
    return "status-ongoing";
  } else if (now < startTime) {
    return "status-upcoming";
  } else {
    return "status-ended";
  }
};

// 导航方法
const goToExamList = () => {
  router.push("/exam-list");
};

const goToExamDetail = (id: string) => {
  router.push(`/exam-detail/${id}`);
};

const goToHistory = () => {
  router.push("/history");
};
</script>

<style scoped>
.home-page {
  padding: 16px;
  padding-bottom: 60px;
}

/* 数据概览 */
.data-overview {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.overview-card {
  flex: 1;
  background-color: #fff;
  border-radius: 8px;
  padding: 16px 8px;
  text-align: center;
  margin: 0 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.overview-value {
  font-size: 20px;
  font-weight: 600;
  color: #1989fa;
  margin-bottom: 4px;
}

.overview-label {
  font-size: 12px;
  color: #969799;
}

/* 快捷操作 */
.quick-actions {
  margin-bottom: 20px;
}

/* 最近考试 */
.recent-exams {
  margin-bottom: 16px;
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  font-size: 16px;
  font-weight: 600;
}

.exam-list {
  margin-top: 12px;
}

.exam-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.exam-name {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 8px;
}

.exam-time {
  font-size: 12px;
  color: #969799;
}

.exam-status {
  font-size: 14px;
  font-weight: 500;
}

.status-ongoing {
  color: #1989fa;
}

.status-upcoming {
  color: #ff976a;
}

.status-ended {
  color: #969799;
}

.loading-container {
  display: flex;
  justify-content: center;
  padding: 24px 0;
}
</style>
